package net.slashie.libjcsi.textcomponents;

import java.util.*;

import net.slashie.libjcsi.CSIColor;
import net.slashie.libjcsi.ConsoleSystemInterface;

/**
 * Displays a list in a box.
 * @author Santiago Zapata
 */
public class ListBox<T> extends TextComponent {
	private static final long serialVersionUID = 5780964313617278066L;

	private final LabelProvider<T> DEFAULT_LABEL_PROVIDER = new LabelProvider<T>() {
		@Override
		public String getText(T item) {
			return item.toString();
		}
	};
	
	private List<Object> itemsList;
	private LabelProvider<T> labelProvider;

    public ListBox(ConsoleSystemInterface si) {
        super(si);
        itemsList = new ArrayList<Object>();
    }

    @Override
	public void draw() {
        clearBox();
        int length = (itemsList.size() < super.inHeight ? itemsList.size() : super.inHeight);
        for (int i = 0; i < length; i++) {
            @SuppressWarnings("unchecked")
			T item = (T) itemsList.get(i);
            String text = labelProvider.getText(item);
            si.print(inPosition.x, inPosition.y + i, (i + 1) + ". ", CSIColor.WHITE);
            if (text.length() > inWidth) {
                text = text.substring(0, inWidth);
            }
            si.print(inPosition.x + 3, inPosition.y + i, text, foreColor);
        }
    }

    public void clearElements() {
    	itemsList.clear();
    }

    public void addElements(Collection<T> elements) {
        itemsList.addAll(elements);
    }
    
    public void setElements(Collection<T> elements) {
    	clearElements();
    	addElements(elements);
    }
    
    public void addElement(T element) {
        itemsList.add(element);
    }

	public void setLabelProvider(LabelProvider<T> labelProvider) {
		if (labelProvider == null) {
			this.labelProvider = DEFAULT_LABEL_PROVIDER;
		} else {
			this.labelProvider = labelProvider;
		}
	}
}

